import React, { createContext, useContext, useReducer, ReactNode } from 'react';

// 消息类型定义
export interface Message {
  type: 'user' | 'bot' | 'action';
  content: string;
  timestamp: string;
  markdown?: boolean;
  action?: any;
  status?: string;
}

// 聊天状态类型定义
interface ChatState {
  messages: Message[];
  inputValue: string;
  isTyping: boolean;
  status: string;
  conversationHistory: any[];
  actionGroups: Map<string, any>;
  currentStreamingAction: string | null;
}

// 聊天动作类型
type ChatAction = 
  | { type: 'SET_MESSAGES'; payload: Message[] }
  | { type: 'ADD_MESSAGE'; payload: Message }
  | { type: 'SET_INPUT_VALUE'; payload: string }
  | { type: 'SET_TYPING'; payload: boolean }
  | { type: 'SET_STATUS'; payload: string }
  | { type: 'SET_CONVERSATION_HISTORY'; payload: any[] }
  | { type: 'SET_ACTION_GROUPS'; payload: Map<string, any> }
  | { type: 'SET_CURRENT_STREAMING_ACTION'; payload: string | null }
  | { type: 'UPDATE_MESSAGE'; payload: { index: number; message: Partial<Message> } }
  | { type: 'RESET_CHAT' };

// 初始状态
const initialState: ChatState = {
  messages: [],
  inputValue: '',
  isTyping: false,
  status: '请先配置 OpenRouter API Key',
  conversationHistory: [],
  actionGroups: new Map(),
  currentStreamingAction: null,
};

// Reducer函数
function chatReducer(state: ChatState, action: ChatAction): ChatState {
  switch (action.type) {
    case 'SET_MESSAGES':
      return { ...state, messages: action.payload };
    case 'ADD_MESSAGE':
      return { ...state, messages: [...state.messages, action.payload] };
    case 'SET_INPUT_VALUE':
      return { ...state, inputValue: action.payload };
    case 'SET_TYPING':
      return { ...state, isTyping: action.payload };
    case 'SET_STATUS':
      return { ...state, status: action.payload };
    case 'SET_CONVERSATION_HISTORY':
      return { ...state, conversationHistory: action.payload };
    case 'SET_ACTION_GROUPS':
      return { ...state, actionGroups: action.payload };
    case 'SET_CURRENT_STREAMING_ACTION':
      return { ...state, currentStreamingAction: action.payload };
    case 'UPDATE_MESSAGE':
      const newMessages = [...state.messages];
      newMessages[action.payload.index] = { ...newMessages[action.payload.index], ...action.payload.message };
      return { ...state, messages: newMessages };
    case 'RESET_CHAT':
      return {
        ...initialState,
        status: state.status, // 保留状态信息
      };
    default:
      return state;
  }
}

// Context类型
interface ChatContextType {
  state: ChatState;
  dispatch: React.Dispatch<ChatAction>;
  // 便捷方法
  setMessages: (messages: Message[]) => void;
  addMessage: (message: Message) => void;
  setInputValue: (value: string) => void;
  setTyping: (typing: boolean) => void;
  setStatus: (status: string) => void;
  setConversationHistory: (history: any[]) => void;
  setActionGroups: (groups: Map<string, any>) => void;
  setCurrentStreamingAction: (actionId: string | null) => void;
  updateMessage: (index: number, message: Partial<Message>) => void;
  resetChat: () => void;
  // 计算属性
  getLastMessage: () => Message | undefined;
  getMessagesByType: (type: 'user' | 'bot' | 'action') => Message[];
}

// 创建Context
const ChatContext = createContext<ChatContextType | undefined>(undefined);

// Provider组件
interface ChatProviderProps {
  children: ReactNode;
}

export function ChatProvider({ children }: ChatProviderProps) {
  const [state, dispatch] = useReducer(chatReducer, initialState);

  // 便捷方法
  const setMessages = (messages: Message[]) => {
    dispatch({ type: 'SET_MESSAGES', payload: messages });
  };

  const addMessage = (message: Message) => {
    dispatch({ type: 'ADD_MESSAGE', payload: message });
  };

  const setInputValue = (value: string) => {
    dispatch({ type: 'SET_INPUT_VALUE', payload: value });
  };

  const setTyping = (typing: boolean) => {
    dispatch({ type: 'SET_TYPING', payload: typing });
  };

  const setStatus = (status: string) => {
    dispatch({ type: 'SET_STATUS', payload: status });
  };

  const setConversationHistory = (history: any[]) => {
    dispatch({ type: 'SET_CONVERSATION_HISTORY', payload: history });
  };

  const setActionGroups = (groups: Map<string, any>) => {
    dispatch({ type: 'SET_ACTION_GROUPS', payload: groups });
  };

  const setCurrentStreamingAction = (actionId: string | null) => {
    dispatch({ type: 'SET_CURRENT_STREAMING_ACTION', payload: actionId });
  };

  const updateMessage = (index: number, message: Partial<Message>) => {
    dispatch({ type: 'UPDATE_MESSAGE', payload: { index, message } });
  };

  const resetChat = () => {
    dispatch({ type: 'RESET_CHAT' });
  };

  // 计算属性
  const getLastMessage = () => {
    return state.messages[state.messages.length - 1];
  };

  const getMessagesByType = (type: 'user' | 'bot' | 'action') => {
    return state.messages.filter(msg => msg.type === type);
  };

  const contextValue: ChatContextType = {
    state,
    dispatch,
    setMessages,
    addMessage,
    setInputValue,
    setTyping,
    setStatus,
    setConversationHistory,
    setActionGroups,
    setCurrentStreamingAction,
    updateMessage,
    resetChat,
    getLastMessage,
    getMessagesByType,
  };

  return (
    <ChatContext.Provider value={contextValue}>
      {children}
    </ChatContext.Provider>
  );
}

// Hook
export function useChat() {
  const context = useContext(ChatContext);
  if (context === undefined) {
    throw new Error('useChat must be used within a ChatProvider');
  }
  return context;
}

// 便捷Hook
export function useChatStatus() {
  const { state, getLastMessage, getMessagesByType } = useChat();
  
  return {
    ...state,
    lastMessage: getLastMessage(),
    userMessages: getMessagesByType('user'),
    botMessages: getMessagesByType('bot'),
    actionMessages: getMessagesByType('action'),
  };
}
